package com.linjiahao.nettyOne.handler;

import com.alibaba.fastjson.JSON;
import com.linjiahao.nettyOne.constant.HandlerServiceName;
import com.linjiahao.servicebase.common.NettyMessageType;
import com.linjiahao.servicebase.common.RabbitPublisher;
import com.linjiahao.servicebase.common.RedisService;
import com.linjiahao.servicebase.vo.NettyMessageVO;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.UnknownHostException;

/**
 * @ClassName WebSockerHandler
 * @Description: 自定义业务handler
 * @Author linjiahao
 * @Date 23/12/2021
 **/
@Component
@Slf4j
@ChannelHandler.Sharable
public class WebSockerHandler extends SimpleChannelInboundHandler<Object> {


    @Resource
    private RedisService redisService;

    @Resource
    private RabbitPublisher rabbitPublisher;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("与客户端建立连接，通道开启,id:{}", ctx.channel().id());
        ChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("与客户端断开连接，通道关闭,id:{}", ctx.channel().id());
        ChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object message) throws InterruptedException, UnknownHostException {
        if (message instanceof FullHttpRequest){
            //以http请求形式接入，但是走的是websocket,首次需要鉴权
            HandlerServiceFactory.getHandlerService(HandlerServiceName.AUTH_HANDLER.getName()).
                    handlerWebsocket(ctx,message);
        }else if (message instanceof TextWebSocketFrame){
            //处理websocket客户端的消息
            TextWebSocketFrame frame = (TextWebSocketFrame)message;
            NettyMessageVO nettyMessageVO = JSON.parseObject(frame.text(), NettyMessageVO.class);
            String name = NettyMessageType.getHandleNameByType(nettyMessageVO.getMessageType());
            log.info("接收到的消息为:{},处理的handler为：{}",nettyMessageVO.toString(), name);
            HandlerServiceFactory.getHandlerService(name).handlerWebsocket(ctx, nettyMessageVO);
        }
    }



}
